package com.purplesoft.zettl.Activities;

import java.text.NumberFormat;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Adapters.ItemListAdapter;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseTables.TblCart;
import com.purplesoft.zettl.DatabaseTables.TblLists;
import com.purplesoft.zettl.DatabaseViews.VwCartItems;
import com.purplesoft.zettl.DatabaseViews.VwPurchaseItems;
import com.purplesoft.zettl.Listener.CartGestureListener;
import com.purplesoft.zettl.Utilities.SharedPrefs;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannedString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Cart extends Activity {

	private ListView lvZettl;
	private TextView tvList, tvAmountItems, tvAmountTotalList, tvAmountTotalCart, tvAmountTotal;
	private Cursor csVwCartItems, csVwPurchaseItems, csTblCart, csTblLists;
	private ItemListAdapter laItems;
	private Dialog dialogImgPopUp;
	private DatabaseExecuter dbExec;
	private View.OnTouchListener gestureListener;
	private SharedPrefs sharedPrefs;
	private final int CURRENT_LIST_ID_DEFAULT_VALUE = -99;
	private final String EQUAL_OPERATION = " = ";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_Purple);
		setContentView(R.layout.cart);
		

		// Bilde Referenzen auf die einzelnen Widgets von zettl.xml
		lvZettl = (ListView) findViewById(R.id.lvListItems_Cart);
		tvList = (TextView) findViewById(R.id.tvList_Cart);
		tvAmountItems = (TextView) findViewById(R.id.tvAmountItems_Cart);
		tvAmountTotalCart = (TextView) findViewById(R.id.tvAmountTotalCart_Cart);
		tvAmountTotalList = (TextView) findViewById(R.id.tvAmountTotalList_Cart);
		tvAmountTotal = (TextView) findViewById(R.id.tvAmountTotal_Cart);
		
		dbExec = new DatabaseExecuter(this);
		sharedPrefs  = new SharedPrefs(this);
		
		csTblLists = dbExec.queryFromTblLists(TblLists.Columns._ID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE), EQUAL_OPERATION);
		csTblLists.moveToFirst();
		startManagingCursor(csTblLists);
		tvList.setText(csTblLists.getString(csTblLists.getColumnIndex(TblLists.Columns.ListName)));

		// Populate list with items from vwPurchaseItems
		csVwCartItems = dbExec.queryFromVwCartItems(VwCartItems.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
//		csVwCartItems = getContentResolver().query(
//				DatabaseContentProvider.VWCartItems, null, null,
//				null, null);
		startManagingCursor(csVwCartItems);
		laItems = new ItemListAdapter(this, csVwCartItems);
		lvZettl.setAdapter(laItems);
		
//		csTblCart = getContentResolver().query(
//				DatabaseContentProvider.TBLCart, null, null, 
//				null, null);
		csTblCart = dbExec.queryFromTblCart(TblCart.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
		startManagingCursor(csTblCart);
		
		calculateTotals();
		
		gestureListener = new CartGestureListener(this, lvZettl);
		
		lvZettl.setOnTouchListener(gestureListener);
		
	}

	private void calculateTotals() {
		double totalList = 0;
		double totalCart = 0;
		double amount = 0;
		double price = 0;
		double pricePer = 0;
		csVwCartItems = dbExec.queryFromVwCartItems(VwCartItems.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
//		csVwCartItems = getContentResolver().query(DatabaseContentProvider.VWCartItems, null, null, null, null);
		startManagingCursor(csVwCartItems);
		csVwCartItems.moveToFirst();
		for (int i = 0; i < csVwCartItems.getCount(); i++) {
			amount = csVwCartItems.getDouble(csVwCartItems.getColumnIndex(VwCartItems.Columns.Amount));
			price = csVwCartItems.getDouble(csVwCartItems.getColumnIndex(VwCartItems.Columns.Price));
			pricePer = csVwCartItems.getDouble(csVwCartItems.getColumnIndex(VwCartItems.Columns.PricePer));
			totalCart = totalCart + ((amount * price) / pricePer);
			if (i < csVwCartItems.getCount()) csVwCartItems.moveToNext();
		}
//		csVwPurchaseItems = getContentResolver().query(DatabaseContentProvider.VWPurchaseItems, null, null,	null, null);
		csVwPurchaseItems = dbExec.queryFromVwPurchaseItems(VwPurchaseItems.Columns.ListID, sharedPrefs.getInt(getResources().getString(R.string.zettl_current_list_id), CURRENT_LIST_ID_DEFAULT_VALUE));
		startManagingCursor(csVwPurchaseItems);
		csVwPurchaseItems.moveToFirst();
		for (int i = 0; i < csVwPurchaseItems.getCount(); i++) {
			amount = csVwPurchaseItems.getDouble(csVwPurchaseItems.getColumnIndex(VwCartItems.Columns.Amount));
			price = csVwPurchaseItems.getDouble(csVwPurchaseItems.getColumnIndex(VwCartItems.Columns.Price));
			pricePer = csVwPurchaseItems.getDouble(csVwPurchaseItems.getColumnIndex(VwCartItems.Columns.PricePer));
			totalList = totalList + ((amount * price) / pricePer);
			if (i < csVwPurchaseItems.getCount()) csVwPurchaseItems.moveToNext();
		}
		int purchaseItemCount = csVwPurchaseItems.getCount();
		int cartCount = csTblCart.getCount();
		tvAmountItems.setText(cartCount + "/" + (cartCount + purchaseItemCount));
		tvAmountTotalList.setText(String.valueOf(NumberFormat.getCurrencyInstance().format(totalList)));
		tvAmountTotalCart.setText(String.valueOf(NumberFormat.getCurrencyInstance().format(totalCart)));
		tvAmountTotal.setText(String.valueOf(NumberFormat.getCurrencyInstance().format(totalCart + totalList)));
	}

	public void showImgPopUp(View view) {
		RelativeLayout attributeRow = (RelativeLayout) view.getParent();
		ImageView ivItemImg = (ImageView) attributeRow.findViewById(R.id.ivItem);
		TextView tvCategoryColor = (TextView) attributeRow.findViewById(R.id.tvCategoryColor);
		TextView tvItem = (TextView) attributeRow.findViewById(R.id.tvItem);
		TextView tvAmountMeasure = (TextView) attributeRow.findViewById(R.id.tvAmountMeasure);
		TextView tvItemDescriptionManufacturer = (TextView) attributeRow.findViewById(R.id.tvItemDescriptionManufacturer);
		TextView tvCategory = (TextView) attributeRow.findViewById(R.id.tvCategory);
		TextView tvPriceMeasure = (TextView) attributeRow.findViewById(R.id.tvPriceMeasure);
		String categoryColor = (String) tvCategoryColor.getTag();
		String imgPath = (String) ivItemImg.getTag();
		String item = (String) tvItem.getText();
		String amountMeasure = (String) tvAmountMeasure.getText();
		SpannedString itemDescriptionManufacturer = null;
		if (tvItemDescriptionManufacturer.getText() instanceof SpannedString) {
			itemDescriptionManufacturer = (SpannedString) tvItemDescriptionManufacturer.getText();
		} else {
			String itemDescriptionManufacturerPlain = (String) tvItemDescriptionManufacturer.getText();
			itemDescriptionManufacturer = new SpannedString(Html.fromHtml(itemDescriptionManufacturerPlain));
		}
		String category = (String) tvCategory.getText();
		String priceMeasure = (String) tvPriceMeasure.getText();
		showPopUp(this, imgPath, categoryColor, item, amountMeasure, itemDescriptionManufacturer, category, priceMeasure);
	}
	
	private void showPopUp(final Activity context, String imgPath, String categoryColor, String itemName, String amountMeasure, SpannedString itemDescriptionManufacturer, String category, String priceMeasure) {
	     
		RelativeLayout viewGroup = (RelativeLayout) context.findViewById(R.id.ZettlImgPopup);
		LayoutInflater layoutInfater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = layoutInfater.inflate(R.layout.zettl_img_popup, viewGroup);
		layout.setBackgroundColor(Color.WHITE);
		
		if (dialogImgPopUp == null || !dialogImgPopUp.isShowing()) {
			dialogImgPopUp = new Dialog(this);
			dialogImgPopUp.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogImgPopUp.setContentView(layout);
			
			WindowManager.LayoutParams lp = dialogImgPopUp.getWindow().getAttributes();
			lp.dimAmount=0.6f;
			dialogImgPopUp.setCanceledOnTouchOutside(true);
			dialogImgPopUp.getWindow().setAttributes(lp);  
			dialogImgPopUp.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			
			ImageView ivItemImg = (ImageView) layout.findViewById(R.id.ivItemImg_ZettlImgPopup);
			TextView tvCategoryColor = (TextView) layout.findViewById(R.id.tvCategoryColor_ZettlImgPopup);
			TextView tvItem = (TextView) layout.findViewById(R.id.tvItem_ZettlImgPopup);
			TextView tvAmountMeasure = (TextView) layout.findViewById(R.id.tvAmountMeasure_ZettlImgPopup);
			TextView tvItemDescriptionManufacturer = (TextView) layout.findViewById(R.id.tvItemDescriptionManufacturer_ZettlImgPopup);
			TextView tvCategory = (TextView) layout.findViewById(R.id.tvCategory_ZettlImgPopup);
			TextView tvPriceMeasure = (TextView) layout.findViewById(R.id.tvPriceMeasure_ZettlImgPopup);
			
			tvCategoryColor.setBackgroundColor(context.getResources().getColor(R.color.transperence));
			
			if (imgPath != null) {
				ivItemImg.setImageBitmap(BitmapFactory.decodeFile(imgPath));
			} else {
				ivItemImg.setImageResource(R.drawable.camera);
			}
			if (categoryColor != null) {
				tvCategoryColor.setBackgroundColor(Color.parseColor(categoryColor));
			}
			tvItem.setText(itemName);
			tvAmountMeasure.setText(amountMeasure);
			tvItemDescriptionManufacturer.setText(itemDescriptionManufacturer);
			tvCategory.setText(category);
			tvPriceMeasure.setText(priceMeasure);
			
			ImageButton btEditItem = (ImageButton) dialogImgPopUp.findViewById(R.id.btEditItem_ZettlImgPopup);
			ImageButton btDeleteItem = (ImageButton) dialogImgPopUp.findViewById(R.id.btDeleteItem_ZettlImgPopup);
			ImageButton btCheckItem = (ImageButton) dialogImgPopUp.findViewById(R.id.btCheckItem_ZettlImgPopup);
			btEditItem.setVisibility(View.INVISIBLE);
			btDeleteItem.setVisibility(View.INVISIBLE);
			btCheckItem.setVisibility(View.INVISIBLE);
			
			dialogImgPopUp.show();
		}
		
	}

}
